package com.example.hyg_veintype.activity.bleConnect;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.hyg_veintype.R;
import com.example.hyg_veintype.activity.bleConnect.adapter.SelectPositionAdapter;
import com.example.hyg_veintype.data.local.analyseLocalBean.PluseAnalyseFuZhongChenWraper;
import com.example.hyg_veintype.data.local.analyseLocalBean.PluseDataWraper;
import com.example.hyg_veintype.activity.result.ResultActivity;
import com.example.hyg_veintype.base.BaseHandler;
import com.example.hyg_veintype.base.BaseVeinTypeActivity;
import com.example.hyg_veintype.constant.ble.BleRssiDevice;
import com.example.hyg_veintype.constant.ble.PreBLEConnectedData;
import com.example.hyg_veintype.utils.chartUtil.RealTimeChartUtils;
import com.example.hyg_veintype.view.guideDialog.GuideDialog;
import com.example.pulseanalyse.PulseAnalyse;
import com.example.pulseanalyse.dealRealPointBLE.PointUtils;
import com.example.pulseanalyse.veinPoint.myClassPluseAnalysisSD;
import com.github.mikephil.charting.charts.LineChart;
import com.hyg.lib_base.mainUtils.ToastUtils;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;


import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback;
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;
import cn.com.heaton.blelibrary.ble.utils.ThreadUtils;
import cn.com.heaton.blelibrary.ble.utils.UuidUtils;

/**
 * author: ${USER}
 * time: ${YEAR}/${MONTH}/${DAY}
 * desc: 蓝牙连接（脉型检测）页面
 */
public class ConnectBLEActivity extends BaseVeinTypeActivity implements BaseHandler.OnReceiveMessageListener {
    public static final String BLETAG = "蓝牙====";
    public static final String JNITAG = "JNI====";
    public static final String EXTRA_TAG = "device";
    //写服务
    private UUID WriteUuidService;
    //写服务的特征值
    private UUID WriteUuidFeatureService;
    //通知服务
    private UUID NotifyUuidService;
    //通知服务的特征值
    private UUID NotifyUuidFeatureService;

    TextView tvBLEName;//蓝牙名称
    TextView tvBLEStatus;//蓝牙连接状态
    TextView tvPressure;
    LineChart chart;//实时折线图
    TextView tvPosition1;//平安脉
    TextView tvPosition2;//全面检测
    RecyclerView rvPosition;//检测位置列表选择器
    Button btControl;//开始、停止控制
    Button btNext;//下一步

    //对外提供所有的蓝牙操作接口
    private Ble<BleDevice> ble;
    private BleDevice bleDevice;
    BaseHandler handler;
    //蓝牙接收后的数据处理工具类
    PointUtils pointUtils;
    //蓝牙通知接口是否已初始化完成
    private volatile boolean hasNotifyInit = false;

    //JNI接口类
    PulseAnalyse pulseAnalyse = new PulseAnalyse();
    //JNI分析回调结果
    PulseAnalyse.PulseInfo pluseType;
    //接收线程
    volatile ScheduledExecutorService getDataService;
    //so方法分析中
    volatile boolean inAnalysising = true;

    //handle发送的蓝牙数据
    public static final int POINT_MSG = 1001;
    public static final String STATICPRESSURE = "StaticPressure";
    public static final String DYNAMICPRESSURE = "dynamicPressure";
    public static final String XVALURE = "index";

    //平安脉位置数据
    private List<PluseDataWraper> positionBeanList1 = new ArrayList<>();
    //全面检测位置数据
    private List<PluseDataWraper> positionBeanList2 = new ArrayList<>();
    //检测位置选择器
    private SelectPositionAdapter positionAdapter;
    //平安脉0、全面检测1标记
    private int veinTypeIndex = 0;
    //平安脉选中标记
    private int veinTypePositionIndex1 = 0;
    //全面检测选中标记
    private int veinTypePositionIndex2 = 0;
    //自动加压控制
    private final int pressureFu = 40;//浮
    private final int pressureZhong = 80;//中
    private final int pressureChen = 160;//沉
    //给设备传的参数，用于记录
    private int nowPressure = pressureFu;

    public static void start(Context context, BleRssiDevice device) {
        Intent starter = new Intent(context, ConnectBLEActivity.class);
        starter.putExtra(ConnectBLEActivity.EXTRA_TAG, device);
        context.startActivity(starter);
    }

    @Override
    public void handlerMessage(Message msg) {
        switch (msg.what) {
            case POINT_MSG:
                //静压
                int staticPressure = msg.getData().getInt(STATICPRESSURE);
                //动压
                int dynamicPressure = msg.getData().getInt(DYNAMICPRESSURE);
                //x坐标值
                int xValure = msg.getData().getInt(XVALURE);
//                Log.d("数据下标=======", xValure + "");
//                Log.d("静压=======", staticPressure + "");
//                Log.d("动压=======", dynamicPressure + "");
                RealTimeChartUtils.addEntry(xValure, dynamicPressure);
                break;
            default:
                break;
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.veintype_activity_connect;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new BaseHandler(this);
        lnTopRight.setVisibility(View.VISIBLE);
        imgRight.setVisibility(View.GONE);
        tvRight.setText("采脉指引");
        initView();
        initData();
        initAdapter();
        //初始化实时折线图
        RealTimeChartUtils.setChart(chart, this, pointUtils.drawPointY);
    }

    private void initView() {
        tvBLEName=findViewById(R.id.tv_ble_name);//蓝牙名称
        tvBLEStatus=findViewById(R.id.tv_ble_status);
        tvPressure=findViewById(R.id.tv_pressure);
        chart=findViewById(R.id.chart);
        tvPosition1=findViewById(R.id.tv_position1);
        tvPosition1.setOnClickListener(this);
        tvPosition2=findViewById(R.id.tv_position2);
        tvPosition2.setOnClickListener(this);
        rvPosition=findViewById(R.id.rv_position);
        btControl=findViewById(R.id.bt_control);
        btControl.setOnClickListener(this);
        btNext=findViewById(R.id.bt_next);
        btNext.setOnClickListener(this);
        lnTopRight.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ln_top_right) {
            GuideDialog guideDialog = new GuideDialog(ConnectBLEActivity.this);
            guideDialog.show();
        } else if (id == R.id.tv_position1) {//平安脉
            veinTypeIndex = 0;
            positionAdapter.updataList(positionBeanList1);
            updateBtControl(positionBeanList1, veinTypePositionIndex1);
            tvPosition1.setBackground(ContextCompat.getDrawable(this, R.drawable.veintype_shape_topright_conner10_white));
            tvPosition2.setBackground(null);
            tvPosition1.setTextColor(ContextCompat.getColor(this, R.color.veintype_main));
            tvPosition2.setTextColor(ContextCompat.getColor(this, R.color.veintype_text_gray));
        } else if (id == R.id.tv_position2) {//全面检测
            veinTypeIndex = 1;
            positionAdapter.updataList(positionBeanList2);
            updateBtControl(positionBeanList2, veinTypePositionIndex2);
            tvPosition1.setBackground(null);
            tvPosition2.setBackground(ContextCompat.getDrawable(this, R.drawable.veintype_shape_topleft_conner10_white));
            tvPosition1.setTextColor(ContextCompat.getColor(this, R.color.veintype_text_gray));
            tvPosition2.setTextColor(ContextCompat.getColor(this, R.color.veintype_main));
        } else if (id == R.id.bt_control) {
            startOrStop();
        } else if (id == R.id.bt_next) {
            if (veinTypeIndex == 0) {
                ResultActivity.start(this, positionBeanList1);
            } else if (veinTypeIndex == 1) {
                ResultActivity.start(this, positionBeanList2);
            }
        }
    }

    /**
     * 开启采集、停止采集
     */
    private void startOrStop() {
        if (!hasNotifyInit) {
            ToastUtils.showShort("蓝牙通知服务初始化中...");
            return;
        }

        String str = btControl.getText().toString();
        if (TextUtils.equals("开始检测", str) || TextUtils.equals("重新检测", str)) {
            //重置检测状态
            upDateTvPressure(1);
            if(veinTypeIndex==0){
                positionBeanList1.get(veinTypePositionIndex1).setStatus(0);
            }else if(veinTypeIndex==1){
                positionBeanList2.get(veinTypePositionIndex2).setStatus(0);
            }
            nowPressure = pressureFu;
            sendStartToBLE();
            closeThread();
            //初始化SO文件分析线程
            initAnalyseThread();
            btControl.setText("停止检测");
        }
        if (TextUtils.equals("停止检测", str)) {
            upDateTvPressure(1);
            btControl.setText("开始检测");
            stopAnalyse();
        }
    }

    /**
     * 停止分析、停止采集
     */
    private void stopAnalyse() {
        nowPressure = pressureFu;
        closeThread();
        sendStopToBLE();
    }

    /**
     * 初始化平安脉、全面检测数据
     */
    private void initAdapter() {
        /************** 平安脉数据构建 **************/
        positionBeanList1.add(new PluseDataWraper("左关", "左-关（肝-胆）", true, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList1.add(new PluseDataWraper("右关", "右-关（脾-胃）", false, 0, new PluseAnalyseFuZhongChenWraper()));
        /************** 全面检测数据构建 **************/
        positionBeanList2.add(new PluseDataWraper("左寸", "左-寸（心-小肠）", true, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList2.add(new PluseDataWraper("右寸", "右-寸（肺-大肠）", false, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList2.add(new PluseDataWraper("左关", "左-关（肝-胆）", false, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList2.add(new PluseDataWraper("右关", "右-关（脾-胃）", false, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList2.add(new PluseDataWraper("左尺", "左-尺（肾-膀胱）", false, 0, new PluseAnalyseFuZhongChenWraper()));
        positionBeanList2.add(new PluseDataWraper("右尺", "右-尺（肾-命门）", false, 0, new PluseAnalyseFuZhongChenWraper()));


        positionAdapter = new SelectPositionAdapter(positionBeanList1, this, new SelectPositionAdapter.OnItemClick() {

            @Override
            public void itemClicked(List<PluseDataWraper> infos, int position) {
                updateBtControl(infos,position);
            }
        });
        rvPosition.setLayoutManager(new GridLayoutManager(this, 2));
        rvPosition.setAdapter(positionAdapter);
    }

    /**
     * 更新底部按钮控制
     * @param infos
     * @param position
     */
    private void updateBtControl(List<PluseDataWraper> infos, int position){
        if (infos.get(position).getStatus() == 0) {
            //未检测
            upDateTvPressure(1);
            btControl.setText("开始检测");
            stopAnalyse();
        } else if (infos.get(position).getStatus() == 1) {
            //检测中
            btControl.setText("停止检测");
        } else if (infos.get(position).getStatus() == 2) {
            //检测完成
            upDateTvPressure(1);
            btControl.setText("重新检测");
            stopAnalyse();
        }
        //记录平安脉/全面检测的列表选中标记
        if (veinTypeIndex == 0) {
            veinTypePositionIndex1 = position;
        } else if (veinTypeIndex == 1) {
            veinTypePositionIndex2 = position;
        }
        //adapter中按钮状态选中
        for (PluseDataWraper mInfo : infos) {
            mInfo.setSelected(false);
        }
        infos.get(position).setSelected(true);
        positionAdapter.notifyDataSetChanged();
    }


    /**
     * 更新当前压力显示文字颜色
     *
     * @param index 40(浮)传1 80（中）传2 160（沉）传3
     */
    private void upDateTvPressure(int index) {
        String preStr = "浮 -> 中 -> 沉";
        SpannableStringBuilder builder = new SpannableStringBuilder(preStr);
        ForegroundColorSpan spanPurper = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.veintype_main));
        ForegroundColorSpan spanred = new ForegroundColorSpan(ContextCompat.getColor(this, R.color.veintype_text_gray2));
        int charIndex = 2;
        if (index == 1) {
            charIndex = 2;
        } else if (index == 2) {
            charIndex = 7;
        } else if (index == 3) {
            charIndex = 11;
        }
        builder.setSpan(spanred, charIndex, preStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        builder.setSpan(spanPurper, 0, charIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvPressure.setText(builder);
    }

    /**
     * 初始化蓝牙服务及特征值服务并连接蓝牙设备
     */
    private void initData() {
        upDateTvPressure(1);
        pointUtils = new PointUtils();
        WriteUuidService = UUID.fromString(UuidUtils.uuid16To128("FFE5"));
        WriteUuidFeatureService = UUID.fromString(UuidUtils.uuid16To128("FFE9"));
        NotifyUuidService = UUID.fromString(UuidUtils.uuid16To128("FFE0"));
        NotifyUuidFeatureService = UUID.fromString(UuidUtils.uuid16To128("FFE4"));
        ble = Ble.getInstance();
        bleDevice = getIntent().getParcelableExtra(EXTRA_TAG);
        tvTitle.setText("脉象采集");
        if (!TextUtils.isEmpty(bleDevice.getBleName())) {
            tvBLEName.setText(bleDevice.getBleName());
        } else {
            tvBLEName.setText("未知设备");
        }
        ble.connect(bleDevice, connectCallback);
    }

    /**
     * 向蓝牙发送开启指令
     */
    private void sendStartToBLE() {
        byte preH = (byte) ((nowPressure >> 8) & 0xFF);
        byte preL = (byte) (nowPressure & 0xFF);
        //开启0xAA,0xCC,0x12,0x03,0x31,PrsH,PrsL,0,0xCC,0xAA  PrsH,PrsL（静压值的初始化）可以手动设置
        byte[] bytes = new byte[]{(byte) 0xAA, (byte) 0xCC, (byte) 0x12, (byte) 0x03, (byte) 0x31,
                preH,
                preL,
                (byte) 0x16, (byte) 0xCC, (byte) 0xAA};
        writeChar(bleDevice, bytes);
    }

    /**
     * 向蓝牙发送关闭指令
     */
    private void sendStopToBLE() {
        //关闭0xAA,0xCC,0x12,0x03,0,0,0,0,0xCC,0xAA
        byte[] bytes = new byte[]{(byte) 0xAA, (byte) 0xCC, (byte) 0x12, (byte) 0x03, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0xCC, (byte) 0xAA};
        writeChar(bleDevice, bytes);
    }

    /**
     * 开启通知服务通知
     *
     * @param turn 是否开启通知服务
     */
    private void enableNotifyByUuid(boolean turn) {
        Ble.getInstance().enableNotifyByUuid(
                bleDevice,
                turn,
                NotifyUuidService,
                NotifyUuidFeatureService,
                notitifyCallback);
    }

    /**
     * 蓝牙通知回调
     */
    BleNotifyCallback<BleDevice> notitifyCallback = new BleNotifyCallback<BleDevice>() {
        @Override
        public void onChanged(BleDevice device, final BluetoothGattCharacteristic characteristic) {
            UUID uuid = characteristic.getUuid();
            if (!uuid.toString().equals(NotifyUuidFeatureService.toString())) {
                return;
            }
//            Log.d(TAG, "onChanged==uuid:" + uuid.toString());
            byte[] bytes = characteristic.getValue();
//            Log.d("characteristic===", characteristic.getValue().length + "");
//            Log.d("getByte[]===", ByteUtils.bytes2HexStr(characteristic.getValue()));
            //判断是否是脉搏数据
            boolean isPressureData = pointUtils.isPressureData(bytes);

            if (isPressureData) {
                int staticPressure = pointUtils.getStaticPressure(characteristic.getValue());//静压值
                int dynamicPressure = pointUtils.getDynamicPressure(characteristic.getValue());//动压值
                int xValue = pointUtils.xValue;
//                Log.d("characteristic===", dynamicPressure + "");
                //开启分析
                int returnValure = pulseAnalyse.setDataToJNI(dynamicPressure);

                Message message = handler.obtainMessage();
                message.what = POINT_MSG;
                Bundle bundle = new Bundle();
                bundle.putInt(STATICPRESSURE, staticPressure);
                bundle.putInt(DYNAMICPRESSURE, dynamicPressure);
                bundle.putInt(XVALURE, xValue);
                message.setData(bundle);
                handler.sendMessage(message);
            }
        }

        @Override
        public void onNotifySuccess(BleDevice device) {
            super.onNotifySuccess(device);
            hasNotifyInit = true;
            ThreadUtils.ui(new Runnable() {
                @Override
                public void run() {
                    // TODO: 2020/11/23 蓝牙设备连接后点击一次写操作（成功）但设备不执行，（硬件人员处理后下面的这行代码可删除）
                    sendStartToBLE();
                    ToastUtils.showShort("Notification已初始化成功");
                    Log.d(BLETAG, "=BLE======onNotifySuccess===");
                }
            });
        }

        @Override
        public void onNotifyCanceled(BleDevice device) {
            super.onNotifyCanceled(device);
            ThreadUtils.ui(new Runnable() {
                @Override
                public void run() {
                    Log.d(BLETAG, "=BLE======onNotifyCanceled===");
                }
            });
        }
    };

    /**
     * 蓝牙数据写入方法
     *
     * @param bleDevice 连接的蓝牙设备
     * @param bytes     数据
     */
    private void writeChar(BleDevice bleDevice, byte[] bytes) {
        Ble.getInstance().writeByUuid(
                bleDevice,
                bytes,
                WriteUuidService,
                WriteUuidFeatureService,
                new BleWriteCallback<BleDevice>() {
                    @Override
                    public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {
                        Log.d(BLETAG, "写入特征成功=====");
                    }

                    @Override
                    public void onWriteFailed(BleDevice device, int failedCode) {
                        super.onWriteFailed(device, failedCode);
                        Log.d(BLETAG, "写入特征失败=====" + failedCode);
                    }
                });
    }

    /**
     * 蓝牙连接回调
     */
    private BleConnectCallback<BleDevice> connectCallback = new BleConnectCallback<BleDevice>() {
        @Override
        public void onConnectionChanged(BleDevice device) {
            Log.d(BLETAG, "onConnectionChanged: " + device.getConnectionState());
            if (device.isConnected()) {
                //存储已连接的蓝牙
                PreBLEConnectedData.setConnectedDeviceData(ConnectBLEActivity.this, device.getBleAddress());
                tvBLEStatus.setText("已连接");
            } else if (device.isConnecting()) {
                tvBLEStatus.setText("连接中...");
            } else if (device.isDisconnected()) {
                tvBLEStatus.setText("未连接");
            }
        }

        @Override
        public void onConnectException(BleDevice device, int errorCode) {
            super.onConnectException(device, errorCode);
            ToastUtils.showShort("连接异常，异常状态码:" + errorCode);
        }

        @Override
        public void onConnectTimeOut(BleDevice device) {
            super.onConnectTimeOut(device);
            Log.d(BLETAG, "onConnectTimeOut: " + device.getBleAddress());
            ToastUtils.showShort("连接超时:" + device.getBleName());
        }

        @Override
        public void onConnectCancel(BleDevice device) {
            super.onConnectCancel(device);
            ToastUtils.showShort("连接取消:" + device.getBleName());
        }

        @Override
        public void onServicesDiscovered(BleDevice device, BluetoothGatt gatt) {
            super.onServicesDiscovered(device, gatt);
        }

        @Override
        public void onReady(BleDevice device) {
            super.onReady(device);
            //连接成功后，开启通知
            Log.d(BLETAG, "onReady==");
            enableNotifyByUuid(true);
        }
    };

    /**
     * 创建一个线程获取so方法的分析结果（so方法为一个while循环所以启线程）
     */
    public void initAnalyseThread() {
        //so方法分析中
        inAnalysising = true;
        getDataService = Executors.newSingleThreadScheduledExecutor();
        getDataService.execute(new TimerTask() {
            @Override
            public void run() {
                //so方法是个while循环，获取结果代表已获得分析结果并跳出
                pluseType = pulseAnalyse.new PulseInfo();
                final int getResultFromJNI = pulseAnalyse.getResultFromJNI(pluseType);
                //分析完毕
                inAnalysising = false;
                Log.d(JNITAG, "====分析结果" + getResultFromJNI);
                //0时获取到了so，返回结果，-1时是点击了跳过操作
                if (getResultFromJNI == 0) {
                    runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {

                            List<Integer> getDataList = new ArrayList<>();
                            List<Integer> getDataListCopy = new ArrayList<>();
                            int[] getData = pluseType.getData();
                            if (getData != null && getData.length > 0) {
                                for (int i = 0; i < pluseType.getData().length; i++) {
                                    getDataListCopy.add(getData[i]);
                                }
                                for (int i = pluseType.getBegin(); i < pluseType.getEnd(); i++) {
                                    getDataList.add(getData[i]);
                                }

                            }
                            //自动加压处理
                            closeThread();
                            dealWithData(getDataListCopy, pluseType.getBegin(), pluseType.getEnd(), pluseType.getBegin() + getDataList.indexOf(Collections.max(getDataList)));
                            if (nowPressure == pressureFu) {
                                nowPressure = pressureZhong;
                                //加压去采集中位
                                upDateTvPressure(2);
                                sendStartToBLE();
                                //初始化SO文件分析线程
                                initAnalyseThread();
                            } else if (nowPressure == pressureZhong) {
                                nowPressure = pressureChen;
                                //加压去采集沉位
                                sendStartToBLE();
                                upDateTvPressure(3);
                                //初始化SO文件分析线程
                                initAnalyseThread();
                            } else if (nowPressure == pressureChen) {
                                //恢复浮脉采集下标
                                nowPressure = pressureFu;
                                upDateTvPressure(1);
                                btControl.setText("重新检测");
                                //检测完成（对号显示）
                                if (veinTypeIndex == 0) {
                                    positionBeanList1.get(veinTypePositionIndex1).setStatus(2);
                                } else if (veinTypeIndex == 1) {
                                    positionBeanList2.get(veinTypePositionIndex2).setStatus(2);
                                }
                                positionAdapter.notifyDataSetChanged();
                                stopAnalyse();
                            }
                        }
                    });
                }

            }
        });
    }

    /**
     * 处理数据(将张帅分析得到的数据存到list集合中)
     *
     * @param pointList
     * @param start
     * @param end
     * @param zhuBoFeng
     */
    private void dealWithData(List<Integer> pointList, int start, int end, int zhuBoFeng) {
        myClassPluseAnalysisSD sd=new myClassPluseAnalysisSD(pointList, start, end, zhuBoFeng);
        if (veinTypeIndex == 0) {
            //平安脉
            if (nowPressure == pressureFu) {
                positionBeanList1.get(veinTypePositionIndex1).getFuZhongChenWraper().setFuSd(sd);
            } else if (nowPressure == pressureZhong) {
                positionBeanList1.get(veinTypePositionIndex1).getFuZhongChenWraper().setZhongSd(sd);
            } else if (nowPressure == pressureChen) {
                positionBeanList1.get(veinTypePositionIndex1).getFuZhongChenWraper().setChenSd(sd);
            }
        } else if (veinTypeIndex == 1) {
            //全面脉
            if (nowPressure == pressureFu) {
                positionBeanList2.get(veinTypePositionIndex2).getFuZhongChenWraper().setFuSd(sd);
            } else if (nowPressure == pressureZhong) {
                positionBeanList2.get(veinTypePositionIndex2).getFuZhongChenWraper().setZhongSd(sd);
            } else if (nowPressure == pressureChen) {
                positionBeanList2.get(veinTypePositionIndex2).getFuZhongChenWraper().setChenSd(sd);
            }
        }
    }


    /**
     * 关闭线程
     * 如果so文件在分析中，则中断分析并关闭线程
     * 如果已获得分析结果，则直接关闭线程
     */
    public void closeThread() {
        if (getDataService == null) {
            return;
        }
        if (inAnalysising) {
            pulseAnalyse.interruptPulseAnalyseJNI();
            getDataService.shutdownNow();
            Log.d(JNITAG, "====中断分析结果并结束线程");
        } else {
            getDataService.shutdownNow();
            Log.d(JNITAG, "====结束线程");
        }
    }

//    @Override
//    protected void onStop() {
//        super.onStop();
//        closeThread();
//        sendStopToBLE();
//        ble.cancelCallback(notitifyCallback);
//        ble.cancelCallback(connectCallback);
//        if (bleDevice != null) {
//            if (bleDevice.isConnecting()) {
//                ble.cancelConnecting(bleDevice);
//            } else if (bleDevice.isConnected()) {
//                ble.disconnect(bleDevice);
//            }
//        }
//    }

    /**
     * 页面关闭时断开蓝牙通知和连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeThread();
        sendStopToBLE();
        ble.cancelCallback(notitifyCallback);
        ble.cancelCallback(connectCallback);
        if (bleDevice != null) {
            if (bleDevice.isConnecting()) {
                ble.cancelConnecting(bleDevice);
            } else if (bleDevice.isConnected()) {
                ble.disconnect(bleDevice);
            }
        }
    }

}
